package com.itheima.controller;

import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {
    @Autowired
    private AliOSSUtils aliOSSUtils;
//    @PostMapping("/upload")
//    public Result upload(String username, Integer age, MultipartFile image) throws Exception {
//        log.info("{}", image);
//
//        //获取原始文件名
//        String OriginalFilename = image.getOriginalFilename();
//
//        //构建唯一的文件名（不能重复）-uuid(通用识别码)
//
//        //获取扩展名.的位置
//        int index = OriginalFilename.lastIndexOf(".");
//        //获取扩展名.jpg
//        String extname = OriginalFilename.substring(index);
//        //uuid拼接
//        String newFileName= UUID.randomUUID().toString()+extname;
//        log.info("新的文件名:{}",newFileName);
//        //将文件储存到指定本地文件中
//        image.transferTo(new File("D:\\new demo\\"+newFileName));
//        return Result.success();
//    }

    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传，文件名：{}",image.getOriginalFilename());

        //调用阿里云oss类文件上传
        String url = aliOSSUtils.upload(image);
        log.info("文件上传完成，文件访问的url：{}",url);

        return Result.success(url);
    }
}
